// src/components/UserProvider.tsx
"use client";

import { useUserStore } from "@/store/userStore";
import { prisma } from "@/lib/db";
import { useEffect, useState } from "react";
import { Spin } from "antd";
import MyLoading from "./MyLoading";

type Props = {
  children?: React.ReactNode;
};

const UserProvider = ({ children }: Props) => {
  const [enabled, setEnabled] = useState(false);
  const [setUser, setLoading, loading] = useUserStore((state) => [
    state.setUser,
    state.setLoading,
    state.loading,
  ]);

  useEffect(() => {
    fetch("/api/user").then(async (res) => {
      const temp = await res.json();
      if (temp.data) {
        const data = temp.data;
        let cu = data.roles.find((it: any) => it.id === data.currentRole)
        setUser({
          id: data.id,
          name: data.name,
          currentRole: data.currentRole,
          roles: data.roles,
          menus: data.menus,
          roleName: cu.name
          // menus:[]
        });
      }
      setLoading(false);
    });
    // prisma.user
    //   .findUnique({
    //     where: {
    //       id: 1,
    //     },
    //   })
    //   .then((data) => {
    //     console.log(data);
    //     // setUser(data);
    //     // setLoading(false);
    //   });
    // setUser(data)
    // setLoading(isLoading)
  }, []);
  if (loading) {
    return (
      <div className="h-[100vh] flex-col w-[100vw] flex justify-center items-center">
        <MyLoading></MyLoading>
        <div className="mt-4">加载中.....</div>
      </div>
    );
  }
  return <>{children}</>;
};

export default UserProvider;
